package com.shwread.android.ui.widget;

import android.content.Context;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.shwread.android.qysw10000182.R;


public abstract class ReadingPopWindow
{
	
	protected volatile PopupWindow popupWindow;
	protected Context              context;
	
	protected void init(Context context, View contentView) {
		this.context = context;
		popupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
		popupWindow.setBackgroundDrawable(context.getResources().getDrawable(R.color.common_transparent));
		popupWindow.setOutsideTouchable(true);// 设置pWindow之外的布局可点击
		popupWindow.setTouchInterceptor(new OnTouchListener()
		{
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				
				if (event.getAction() == MotionEvent.ACTION_OUTSIDE)
				{
					popupWindow.dismiss();
					return true;
				}
				return false;
			}
		});
		initView(contentView);
		addListener();
	}
	
	protected abstract void addListener();
	
	protected abstract void initView(View parentView);
	
	public void showSelection(View viewParent, int selectionStartY, int selectionEndY) {
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
		layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
		
		final int verticalPosition;
		final int screenHeight = ((View)viewParent.getParent()).getHeight();
		final int diffTop = screenHeight - selectionEndY;
		final int diffBottom = selectionStartY;
		if (diffTop > diffBottom)
		{
			verticalPosition = diffTop > popupWindow.getHeight() + 20 ? RelativeLayout.ALIGN_PARENT_BOTTOM : RelativeLayout.CENTER_VERTICAL;
		}
		else
		{
			verticalPosition = diffBottom > popupWindow.getHeight() + 20 ? RelativeLayout.ALIGN_PARENT_TOP : RelativeLayout.CENTER_VERTICAL;
		}
		
		popupWindow.setFocusable(true);
		popupWindow.showAtLocation(viewParent, Gravity.CENTER_HORIZONTAL, 0, verticalPosition);
	}
	
	public void showBottom(View viewParent) {
		popupWindow.setFocusable(true);
		popupWindow.showAtLocation(viewParent, Gravity.BOTTOM, 0, 0);
	}
}
